/**
 * @Description: 组件工具函数类
 * @Author: gengzhaoji
 */
import { Suspense } from 'react';
import Guard from './guard';

export default class Fn {
	constructor(option) {
		this.routes = option.routes || [];
		this.onRouteBefore = option.onRouteBefore;
		this.loading = option.loading || <div></div>;
	}

	/**
	 * @description: 路由配置列表数据转换
	 * @param {string} redirect 要重定向的路由路径
	 * @param {function} element 函数形式import懒加载组件
	 * @param {object} meta 自定义字段
	 */
	transformRoutes(routeList = this.routes) {
		const list = [];
		routeList.forEach((route) => {
			const obj = { ...route };
			if (obj.path === undefined) return;

			if (obj.redirect) {
				obj.element = <Navigate to={obj.redirect} replace={true} />;
			} else if (isFunction(obj.element)) {
				obj.element = this.lazyLoad(obj.element, obj.meta || {});
			}
			delete obj.redirect;
			delete obj.meta;

			// 递归调用
			if (obj.children) obj.children = this.transformRoutes(obj.children);

			list.push(obj);
		});
		return list;
	}

	/**
	 * @description: 路由懒加载
	 */
	lazyLoad(importFn, meta) {
		const Element = memo(lazy(importFn));
		const lazyElement = (
			<Suspense fallback={this.loading}>
				<Element _meta={meta} />
			</Suspense>
		);
		return <Guard element={lazyElement} meta={meta} onRouteBefore={this.onRouteBefore} />;
	}
}
